﻿namespace EyeOpen.EmbeddedExecutable.Shell
{
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;
    using System.Resources;

    internal class Program
    {
        public static void Main()
        {
            var assembly = Assembly.GetExecutingAssembly();
            
            var resourceName = 
                assembly.GetName().Name + ".EyeOpen.EmbeddedExecutable.Windows.exe";

            var filePath = Path.Combine(Path.GetTempPath(), resourceName);

            ExtractResourceToFile(assembly, resourceName, filePath);

            Process.Start(filePath);
        }

        private static void ExtractResourceToFile(Assembly assembly, string resourceName, string filePath)
        {
            using (var stream = assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    throw new MissingManifestResourceException();
                }

                WriteStreamToFile(stream, filePath);
            }
        }

        private static void WriteStreamToFile(Stream stream, string filePath)
        {
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);

            using (var writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
            {
                writer.Write(buffer);
            }
        }
    }
}